package com.gin.kotlin.no_gay_alliance.activity

import android.content.Context
import android.content.Intent
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingActivity
import com.gin.kotlin.no_gay_alliance.databinding.ActivitySignatureEditBinding
import com.gin.nga.callback.NgaCallback
import com.gin.nga.response.base.NgaResponse
import retrofit2.Call
import retrofit2.Response

class SignatureEditActivity : AbstractBindingActivity<ActivitySignatureEditBinding>(), NgaCallback<List<String>> {
    private var userId: Long = 0L
    private lateinit var signature: String

    override fun onCreate() {
        val b = this.b ?: return
        b.etContent.setText(signature)

    }

    override fun onResume() {
        super.onResume()
        setToolbarTitle("修改签名")
    }

    override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
        menuInflater.inflate(R.menu.save, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.mi_save) {
            b?.etContent?.text?.toString()?.also {
                App.INSTANCE.ngaApi.accountApi.signatureSet(this.userId, it).enqueue(this)
            }

            return true
        }

        return super.onOptionsItemSelected(item)
    }

    override fun onSuccess(call: Call<NgaResponse<List<String>>>, response: Response<NgaResponse<List<String>>>, body: NgaResponse<List<String>>?, data: List<String>?) {
        data?.get(0)?.also { toast(it) }
    }

    override fun onError(call: Call<NgaResponse<List<String>>>, response: Response<NgaResponse<List<String>>>, body: NgaResponse<List<String>>?, errorMessage: String) {
        super.onError(call, response, body, errorMessage)
        toastLong(errorMessage)
    }

    override fun handleIntent(intent: Intent) {
        this.signature = intent.getStringExtra(KEY_SIGNATURE)?.replace("<br/*>".toRegex(), "\n") ?: ""
        this.userId = intent.getLongExtra(KEY_USER_ID, App.INSTANCE.account.userId)
    }

    companion object {
        private const val KEY_SIGNATURE = "signature"
        private const val KEY_USER_ID = "user_id"

        @JvmStatic
        fun start(context: Context, signature: String? = null, userId: Long? = null) =
            context.startActivity(
                Intent(context, SignatureEditActivity::class.java)
                    .putExtra(KEY_SIGNATURE, signature)
                    .putExtra(KEY_USER_ID, userId)
            )
    }
}